package com.example.translationapp.slice;

import com.example.translationapp.ResourceTable;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.net.NetHandle;
import ohos.net.NetManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import static ohos.hiviewdfx.HiLog.LOG_APP;

public class MainAbilitySlice extends AbilitySlice {
    private TextField TextField01;
    private Button button01;
    private Text result01;

    private final HiLogLabel LOG_LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");

    //定义一个内部类
    class XEventHandler extends EventHandler {
        public XEventHandler(EventRunner runner) throws IllegalArgumentException{
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);

            switch (event.eventId){
                case 1:
                    String result = (String) event.object;
                    result01.setText(result);
                    break;
                default:
                    break;
            }
        }
    }
    private EventRunner eventRunner;
    private EventHandler eventHandler;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        TextField01 = (TextField) findComponentById(ResourceTable.Id_TextField01);
        result01 = (Text) findComponentById(ResourceTable.Id_result01);
        button01 = (Button) findComponentById(ResourceTable.Id_button01);

        // 为按钮设置点击事件回调
        button01.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                // 此处添加点击按钮后的事件处理逻辑

                //取得用户在文本框输入的文本
                String inputWord = TextField01.getText();

                // 用户输入的内容在日志打印
                HiLog.info(LOG_LABEL, inputWord);
                //doTranslate(inputWord);

                //进行异步调用

                //GlobalTaskDispatcher
                //全局并发任务分发器，由Ability执行getGlobalTaskDispatcher()获取。适用于任务之间没有联系的情况。
                // 一个应用只有一个GlobalTaskDispatcher，它在程序结束时才被销毁。
                TaskDispatcher taskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);

                //asyncDispatch
                //异步派发任务：派发任务，并立即返回，返回值是一个可用于取消任务的接口
                taskDispatcher.asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        String result = doTranslate(inputWord);

                        //通过线程通讯的方式向主线程发送事件
                        InnerEvent evt = InnerEvent.get(1);
                        evt.object = result;
                        eventHandler.sendEvent(evt);
                    }
                });
            }
        });

        //与主线程绑定的eventRunner
        eventRunner = eventRunner.getMainEventRunner();
        eventHandler = new XEventHandler(eventRunner);

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    //私有方法接收用户的输入内容
    private String doTranslate(String word) {
        //调用NetManager.getInstance(Context)获取网络管理的实例对象
        NetManager netManager = NetManager.getInstance(null);

        //检测是否有缺省的网络环境
        if (!netManager.hasDefaultNet()) {
            return "";
        }

        //调用NetManager.getDefaultNet()获取默认的数据网络
        NetHandle netHandle = netManager.getDefaultNet();

        String resText = "";
        // 通过openConnection来获取URLConnection
        HttpURLConnection connection = null;
        try {
            String urlString = String.format("https://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=%s", word); // 开发者根据实际情况自定义EXAMPLE_URL
            URL url = new URL(urlString);

            //调用NetHandle.openConnection()打开一个URL
            URLConnection urlConnection = netHandle.openConnection(url,
                    java.net.Proxy.NO_PROXY);
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection) urlConnection;
            }
            connection.setRequestMethod("GET");
            connection.connect();

            // 之后可进行url的其他操作
            //获取http后返回的内容
            InputStream in = connection.getInputStream();

            //下面对获取的输入流进行读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            //输出返回的内容
            HiLog.info(LOG_LABEL, response.toString());

            resText = response.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        //return resText;
        return parseTranslationResult(resText);
    }

    // 私有方法，调用网易有道翻译API的得到的结果，并输出最终的翻译结果
    private String parseTranslationResult(String transApiResponseText){
        String result = "";

        // 调用JsonParser对transApiResponseText整个json进行解析
        JsonElement jsonElement = JsonParser.parseString(transApiResponseText);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        // 调取errorCode为0时能正常输出
        int errorCode = jsonObject.get("errorCode").getAsInt();

        //通过根节点获取translateResult节点一个数组对象
        JsonArray translateResult = jsonObject.get("translateResult").getAsJsonArray();
        //获取第一个子节点的子节点json对象，也是一个数组
        JsonObject jsonObject1 = translateResult.get(0).getAsJsonArray().get(0).getAsJsonObject();
        result = jsonObject1.get("tgt").getAsString();

        return result;
    }
}

